<?php

namespace app\common\logic;

use app\admin\model\Admin;
use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Car;
use app\common\model\CarImages;
use app\common\model\CarImagesShop;
use app\common\model\CarImagesShopRecord;
use app\common\model\CarModels;
use app\common\model\CarSeries;
use app\common\model\Message;
use app\common\model\Order;
use think\db\Query;
use think\Exception;
use think\Queue;


class CarLogic extends BaseLogic
{
    public $model;


    public function assignModel()
    {
        $this->model               = new Car();
    }

    /**
     * 搜索条件处理
     * @param Query $query
     * @param array $params
     * @return Query
     */
    public function handleSearch(Query $query, array $params): Query
    {
        if(isset($params['member_id']) && !empty($params['member_id'])) {
            $query->where('fa_car.member_id', $params['member_id']);
        }
        if(isset($params['is_del'])) {
            $query->where('fa_car.is_del', $params['is_del']);
        }
        return $query;
    }

    /**
     * 我的车库
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $params['member_id'] = $this->memberId;
        $params['is_del'] = 0;
        $params['with'] = ['brand','series'];
        $params['field'] = "id,is_default,car_numbers";
        $params['orderBy'] = ['is_default','createtime'];
        $params['orderType'] = ['desc','desc'];
        return $this->getPageList($params)->each(function (&$item){
            $item['name'] = $item['brand']['name'] ?? '';
            $item['logo'] = $item['brand']['logo'];
            $item['series_name'] = $item['series']['name'] ?? '';
            unset($item['brand'],$item['series']);
            return $item;
        });
    }

    /**
     * 添加车辆
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

//    public function adds($params)
//    {
//        $params['member_id'] = $this->memberId;
//        $params['is_default'] = 0;
//        $default_info = $this::first(['member_id'=>$this->memberId,'is_del'=>0,'is_default'=>1]); //获取默认的车辆信息
//        if (empty($default_info))
//            $params['is_default'] = 1;
//        $info = Car::create($params,"member_id,car_numbers,brand_id,series_id,models_id,car_type,travel_time,vin,mileage,is_default");
//        if (isset($params['images']) && !empty($params['images'])){ //添加汽车图片
//            foreach ($params['images'] as &$value){
//                $value['car_id'] = $info->id;
//                $value['new_url'] = $value['url'];
//                unset($value['url']);
//            }
//            CarImages::insertAll($params['images']);
//        }
//        return [];
//    }

    /**
     * 添加车辆
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add($params)
    {
        if (isset($params['models_id']) && !empty($params['models_id'])){
            //根据车系获取品牌
            $models_info = CarModels::get($params['models_id']);
            if (empty($models_info))
                throw new ApiException("车型信息不存在",404);
            $params['brand_id'] = $models_info['brand_id'];
            $params['series_id'] = $models_info['series_id'];
        }else{
            if (isset($params['series_id']) && !empty($params['series_id'])){
                //根据车系获取品牌
                $series_info = CarSeries::get($params['series_id']);
                if (empty($series_info))
                    throw new ApiException("车系信息不存在",404);
                $params['brand_id'] = $series_info['brand_id'];
                $params['models_id'] = 0;
            }
        }
        $is_default = 0;
        $default_info = Car::get(['member_id' => MemberVo::instance()->getMemberId(), 'is_del' => 0, 'is_default' => 1]);
        if (empty($default_info))
            $is_default = 1;
        //查询车牌号
        $info = Car::get(['member_id' => MemberVo::instance()->getMemberId(), 'car_numbers'=>$params['car_numbers'],'is_del'=>0]);
        if ($info)
            throw new ApiException("该车辆已存在，请勿重复添加",404);
        if (!empty($params['travel_time'])){
            $res = Car::create(['member_id' => MemberVo::instance()->getMemberId(),'car_numbers'=>$params['car_numbers'],'brand_id' => $params['brand_id'] ?? 0, 'series_id' => $params['series_id'] ?? 0,'models_id'=>$params['models_id'] ?? 0,'car_type'=>$params['car_type'] ?? '','mileage' => $params['mileage'] ?? 0, 'vin' => $params['vin'] ?? '','travel_time' => $params['travel_time'], 'is_default' => $is_default]);
        }else{
            $res = Car::create(['member_id' => MemberVo::instance()->getMemberId(),'car_numbers'=>$params['car_numbers'],'brand_id' => $params['brand_id'] ?? 0, 'series_id' => $params['series_id'] ?? 0,'models_id'=>$params['models_id'] ?? 0,'car_type'=>$params['car_type'] ?? '','mileage' => $params['mileage'] ?? 0, 'vin' => $params['vin'] ?? '', 'is_default' => $is_default]);
        }
        return $res->id;
    }


    public function info($params)
    {
        if (!isset($params['id']) || empty($params['id'])){
            $default_info = Car::get(['member_id'=>MemberVo::instance()->getMemberId(),'is_del'=>0,'is_default'=>1]);
            if (!$default_info)
                return [];
            $car_id = $default_info['id'];
        }else{
            $car_id = $params['id'];
        }
        $car_info = Car::get(['car.member_id'=>MemberVo::instance()->getMemberId(),'car.id'=>$car_id,'car.is_del'=>0],['brand','series']);
        if (!$car_info){
            throw new ApiException("车辆信息不存在",404);
        }
        return $car_info;

    }

    /**
     * 车辆信息更新
     */
    public function updates($params)
    {
        if (!empty($params['travel_time'])){
            Car::update([
                'car_numbers' => $params['car_numbers'], 'car_type' => $params['car_type'],
                'mileage' => $params['mileage'], 'vin' => $params['vin'], 'travel_time' => $params['travel_time']], ['id' => $params['id']]);
        }else{
            Car::update([
                'car_numbers' => $params['car_numbers'], 'car_type' => $params['car_type'],
                'mileage' => $params['mileage'], 'vin' => $params['vin']], ['id' => $params['id']]);
        }

        return true;
    }

    /**
     * 车辆图片更新
     * @param $params
     * @return array|bool
     * @throws \think\exception\DbException
     */
    public function update_picture($params)
    {
        if (empty($params['images']))
            return [];
        foreach ($params['images'] as &$item){
            $info = CarImages::get(['car_id'=>$params['id'],'type'=>$item['type']]);
            if (empty($info)){
                $item['car_id'] = $params['id'];
                $item['new_url'] = $item['url'];
                $item['status'] = 0;
                unset($item['url']);
                CarImages::create($item);
            }else{
                CarImages::update(['new_url'=>$item['url'],'status'=>0],['id'=>$info['id']]);
            }
        }
        Message::create(['content'=>"有新的车辆图片待审核，请及时处理！"]);
        $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
        foreach ($admins as $v){
            Queue::push(\app\job\Message::class,[
                'member_id'=>$v['member_id'],
                'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                'data'=>[
                    'thing13'=>"车辆图片待审核工单",
                    'phrase3'=> '车主',
                    'time4'=>date('Y-m-d H:i')
                ]
            ],'message');
        }
        return true;
    }


    /**
     * 车辆图片更新(商家端视角)
     * @param $params
     * @return array|bool
     * @throws \think\exception\DbException
     */
    public function update_picture_shop($params)
    {
        if (empty($params['images']))
            return [];
        foreach ($params['images'] as &$item){
            $info = CarImagesShopRecord::get(['car_id'=>$params['id'],'type'=>$item['type'],'shop_id'=>MemberVo::instance()->getShopId()]);
            if (empty($info)){
                CarImagesShopRecord::create(['car_id'=>$params['id'],'type'=>$item['type'],'url'=>$item['url'],'shop_id'=>MemberVo::instance()->getShopId()]);
            }else{
                $info->url = $item['url'];
                $info->status = 0;
                $info->save();
            }
        }
        Message::create(['content'=>"有新的车辆图片待审核，请及时处理！"]);
        $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
        foreach ($admins as $v){
            Queue::push(\app\job\Message::class,[
                'member_id'=>$v['member_id'],
                'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                'data'=>[
                    'thing13'=>"车辆图片待审核工单",
                    'phrase3'=> '商家',
                    'time4'=>date('Y-m-d H:i')
                ]
            ],'message');
        }
        return true;
    }


    /**
     * 车架号或者车牌查用户信息
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search($params)
    {
        $info = Car::where('car_numbers','like','%'.$params['keyword'].'%')->whereOr('vin','like','%'.$params['keyword'].'%')->find();
        if (empty($info))
            return [];
        //查看是否有核销记录
        $order = Order::get(['shop_id'=>MemberVo::instance()->getShopId(),'member_id'=>$info['member_id'],'order_status'=>['in',[Order::ORDER_STATUS_WAIT_COMMENT, Order::ORDER_STATUS_OK]]]);
        if ($order){
            return ['type'=>1,'member_id'=>$order['member_id'],'audit_code'=>''];
        }
        //查看是否有待核销的订单
        $order = Order::get(['shop_id'=>MemberVo::instance()->getShopId(),'member_id'=>$info['member_id'],'order_status'=>Order::ORDER_STATUS_WAIT_AUDIT]);
        if ($order)
            return ['type'=>2,'member_id'=>$order['member_id'],'audit_code'=>$order['audit_code']];
        return [];
    }


    public function moreInfo($params)
    {
        try{
            $imgs = CarImages::all(['car_id'=>$params['id']])->toArray();
            if (!empty($imgs)){
                foreach ($imgs as &$v){
                    $v['type'] = 'img_'.$v['type'];
                }
            }
            $imgs_new = array_column($imgs,NULL,'type');
            $data[] = ['name' => '车辆详情图-证件照', 'list' => [
                ['name' => '行驶证正面照', 'type' => 1, 'url' => isset($imgs_new['img_1']) ? ($imgs_new['img_1']['status']  === 1 ? $imgs_new['img_1']['url'] : $imgs_new['img_1']['new_url']) : '','status'=>isset($imgs_new['img_1']) ? $imgs_new['img_1']['status'] : ''],
                ['name' => '行驶证反面照', 'type' => 2, 'url' => isset($imgs_new['img_2']) ? ($imgs_new['img_2']['status']  === 1 ? $imgs_new['img_2']['url'] : $imgs_new['img_2']['new_url']) : '','status'=>isset($imgs_new['img_2']) ? $imgs_new['img_2']['status'] : '']]];

            $data[] = ['name' => '车辆详情图-车外观', 'list' => [
                ['name' => '车外观左侧照', 'type' => 3, 'url' => isset($imgs_new['img_3']) ? ($imgs_new['img_3']['status']  === 1 ? $imgs_new['img_3']['url'] : $imgs_new['img_3']['new_url']) : '','status'=>isset($imgs_new['img_3']) ? $imgs_new['img_3']['status'] : ''],
                ['name' => '车外观右侧照', 'type' => 4, 'url' => isset($imgs_new['img_4']) ? ($imgs_new['img_4']['status']  === 1 ? $imgs_new['img_4']['url'] : $imgs_new['img_4']['new_url']) : '','status'=>isset($imgs_new['img_4']) ? $imgs_new['img_4']['status'] : ''],
                ['name' => '车外观车头照', 'type' => 5, 'url' => isset($imgs_new['img_5']) ? ($imgs_new['img_5']['status']  === 1 ? $imgs_new['img_5']['url'] : $imgs_new['img_5']['new_url']) : '','status'=>isset($imgs_new['img_5']) ? $imgs_new['img_5']['status'] : ''],
                ['name' => '车外观车尾照', 'type' => 6, 'url' => isset($imgs_new['img_6']) ? ($imgs_new['img_6']['status']  === 1 ? $imgs_new['img_6']['url'] : $imgs_new['img_6']['new_url']) : '','status'=>isset($imgs_new['img_6']) ? $imgs_new['img_6']['status'] : '']]];

            $data[] = ['name'=>'车辆详情图-车内饰','list'=>[
                ['name'=>'主驾驶照','type'=>7, 'url' => isset($imgs_new['img_7']) ? ($imgs_new['img_7']['status']  === 1 ? $imgs_new['img_7']['url'] : $imgs_new['img_7']['new_url']) : '','status'=>isset($imgs_new['img_7']) ? $imgs_new['img_7']['status'] : ''],
                ['name'=>'副驾驶照','type'=>8, 'url' => isset($imgs_new['img_8']) ? ($imgs_new['img_8']['status']  === 1 ? $imgs_new['img_8']['url'] : $imgs_new['img_8']['new_url']) : '','status'=>isset($imgs_new['img_8']) ? $imgs_new['img_8']['status'] : ''],
                ['name'=>'中控台照','type'=>9, 'url' => isset($imgs_new['img_9']) ? ($imgs_new['img_9']['status']  === 1 ? $imgs_new['img_9']['url'] : $imgs_new['img_9']['new_url']) : '','status'=>isset($imgs_new['img_9']) ? $imgs_new['img_9']['status'] : ''],
                ['name'=>'后排照','type'=>10, 'url' => isset($imgs_new['img_10']) ? ($imgs_new['img_10']['status']  === 1 ? $imgs_new['img_10']['url'] : $imgs_new['img_10']['new_url']) : '','status'=>isset($imgs_new['img_10']) ? $imgs_new['img_10']['status'] : '']]];

            $data[] = ['name'=>'车辆详情图-车轮','list'=>[
                ['name'=>'左前轮照','type'=>11,'url' => isset($imgs_new['img_11']) ? ($imgs_new['img_11']['status']  === 1 ? $imgs_new['img_11']['url'] : $imgs_new['img_11']['new_url']) : '','status'=>isset($imgs_new['img_11']) ? $imgs_new['img_11']['status'] : ''],
                ['name'=>'左后轮照','type'=>12,'url' => isset($imgs_new['img_12']) ? ($imgs_new['img_12']['status']  === 1 ? $imgs_new['img_12']['url'] : $imgs_new['img_12']['new_url']) : '','status'=>isset($imgs_new['img_12']) ? $imgs_new['img_12']['status'] : ''],
                ['name'=>'右前轮照','type'=>13,'url' => isset($imgs_new['img_13']) ? ($imgs_new['img_13']['status']  === 1 ? $imgs_new['img_13']['url'] : $imgs_new['img_13']['new_url']) : '','status'=>isset($imgs_new['img_13']) ? $imgs_new['img_13']['status'] : ''],
                ['name'=>'右后轮照','type'=>14,'url' => isset($imgs_new['img_14']) ? ($imgs_new['img_14']['status']  === 1 ? $imgs_new['img_14']['url'] : $imgs_new['img_14']['new_url']) : '','status'=>isset($imgs_new['img_14']) ? $imgs_new['img_14']['status'] : '']]];

            $data[] = ['name'=>'车辆详情图-发动机/蓄电池','list'=>[
                ['name'=>'发动机舱照','type'=>15,'url' => isset($imgs_new['img_15']) ? ($imgs_new['img_15']['status']  === 1 ? $imgs_new['img_15']['url'] : $imgs_new['img_15']['new_url']) : '','status'=>isset($imgs_new['img_15']) ? $imgs_new['img_15']['status'] : ''],
                ['name'=>'蓄电池照','type'=>16,'url' => isset($imgs_new['img_16']) ? ($imgs_new['img_16']['status']  === 1 ? $imgs_new['img_16']['url'] : $imgs_new['img_16']['new_url']) : '','status'=>isset($imgs_new['img_16']) ? $imgs_new['img_16']['status'] : '']]
            ];
            return $data;
        }catch (Exception $e){
            throw new ApiException($e->getMessage(),404);
        }
    }
}